package public

import (
	"server/game/cache"
	"server/game/model"
	"server/share/config"

	"github.com/hwcer/cosgo/registry"
	"github.com/hwcer/yyds/context"
	"github.com/hwcer/yyds/errors"
)

var Egg = &egg{}

func init() {
	Register(Egg)
}

type egg struct {
}

func (this *egg) Caller(node *registry.Node, handle *context.Context) interface{} {
	f := node.Method().(func(*egg, *context.Context) interface{})
	return f(this, handle)
}

/**
 * @name setEgg
 * @param json egg  siteID位置ID:eggID
 * 把蛋放到孵化器上
 */
func (this *egg) SetEgg(c *context.Context) interface{} {
	args := struct {
		Egg struct {
			SiteID int32 `json:"siteID"`
			EggID  int32 `json:"eggID"`
		} `json:"egg" bson:"egg"`
	}{}
	if err := c.Bind(&args); err != nil {
		return err
	}
	if args.Egg.EggID == 0 || args.Egg.SiteID == 0 {
		return errors.ErrArgEmpty
	}
	if cfg := config.Data.Egg[args.Egg.EggID]; cfg == nil {
		return errors.ErrConfigEmpty
	}

	incubator := config.Data.Incubator[args.Egg.SiteID]
	if incubator == nil {
		return errors.ErrConfigEmpty
	}
	if incubator.UnlockBuildLevel > 0 {
		return c.Error("未解锁")
	}
	doc := cache.GetRole(c.Player.Updater)
	role := doc.All()

	incubateList := role.IncubateList.Clone()
	if data := incubateList[args.Egg.SiteID]; data != nil && data.Egg > 0 {
		return c.Error("site busy")
	}
	incubateList[args.Egg.SiteID] = &model.Incubate{
		Egg:  args.Egg.EggID,
		Time: c.Milli(),
	}
	c.Player.Sub(args.Egg.EggID, 1)
	doc.Set("incubateList", incubateList)

	return true
}

/**
 * @name openEgg
 * @param int siteID
 * 开蛋
 */
func (this *egg) OpenEgg(c *context.Context) interface{} {
	siteID := c.GetInt32("siteID")
	if siteID == 0 {
		return errors.ErrArgEmpty
	}
	doc := cache.GetRole(c.Player.Updater)
	role := doc.All()
	incubateList := role.IncubateList.Clone()
	data := incubateList[siteID]
	if data == nil {
		return errors.ErrArgEmpty
	}
	cfg := config.Data.Egg[data.Egg]
	if cfg == nil {
		return errors.ErrConfigEmpty
	}
	if c.Milli()-data.Time < int64(cfg.Time*1000) {
		return c.Error("M2saghge40")
	}
	c.Player.Add(cfg.ItemGroup, 1)
	delete(incubateList, siteID)
	doc.Set("incubateList", incubateList)
	c.Player.Emit(config.Data.Events.EggIncubation, 1)
	return true
}

/**
 * @name boostEgg
 * @param int siteID
 * 孵化加速
 */

func (this *egg) BoostEgg(c *context.Context) interface{} {
	siteID := c.GetInt32("siteID")
	if siteID == 0 {
		return errors.ErrArgEmpty
	}
	doc := cache.GetRole(c.Player.Updater)
	role := doc.All()
	incubateList := role.IncubateList.Clone()
	data := incubateList[siteID]
	if data == nil {
		return errors.ErrArgEmpty
	}
	cfg := config.Data.Egg[data.Egg]
	if cfg == nil {
		return errors.ErrConfigEmpty
	}
	if c.Milli()-data.Time >= int64(cfg.Time*1000) {
		return c.Error("已经完成孵化，不需要加速")
	}
	data.Time -= int64(cfg.Time * 1000)
	doc.Set("incubateList", incubateList)
	c.Player.Sub(60600003, 1)
	return true
}
